package com.itheima.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.po.User;
import com.itheima.service.UserService;
@Controller
public class UserController {
	@Autowired
	private UserService userService;
	/*
	 * 用户注册
	 */
	@RequestMapping(value="/register.action")
	@ResponseBody
	public JSONObject register(User user) {
		user.setStatus("ord");
		user.setUsercover("defaultCover");
		JSONObject json = new JSONObject();
		int row = userService.register(user);
		if(row>0)
			json.put("status", "succeed");
		else
			json.put("status", "failed");
		return json;
	}
	/*
	 * 验证用户id是否已存在
	 */
	@RequestMapping(value="/validate.action")
	@ResponseBody
	public JSONObject validate(User user) {
		user = userService.findUser(user);
		JSONObject json = new JSONObject();
		if(user!=null)
			json.put("status", "failed");
		else
			json.put("status", "succeed");
		return json;
			
	}

	/*
	 * 用户登录
	 */
	@RequestMapping(value="/login.action")
	@ResponseBody
	public JSONObject login(User user,HttpSession session) {
		user = userService.findUser(user);
		JSONObject json = new JSONObject();
		if(user!=null) {
			
			if(user.getStatus().equals("ord")) {
				session.setAttribute("USER_SESSION", user);
				json.put("status", "succeed");
				json.put("type","ord");
				json.put("nickname", user.getNickname());
				json.put("usercover", user.getUsercover());
				json.put("gender", user.getGender());
			}else if(user.getStatus().equals("admin")) {
				session.setAttribute("USER_SESSION", user);
				json.put("status", "succeed");
				json.put("type", "admin");
				json.put("nickname", user.getNickname());
				json.put("usercover", user.getUsercover());
			}
		}else {
			json.put("status","fail");
		}
		System.out.println(json);
		return json;
	}

	/*
	 * 获取用户所有信息
	 */
	@RequestMapping(value="/getUserInfo.action")
	@ResponseBody
	public JSONObject getUserInfo(HttpSession session) {
		User user = (User)session.getAttribute("USER_SESSION");
		JSONObject json = new JSONObject();
		if(user!=null) {
			json.put("nickname",user.getNickname());
			json.put("usercover", user.getUsercover());
			json.put("email", user.getEmail());
		}
		return json;
	}
	/*
	 * 用户修改个人信息（除密码）
	 */
	@RequestMapping(value="/changeUserInfo.action")
	@ResponseBody
	public JSONObject changeUserInfo(User user,HttpSession session) {
		user.setUserid(((User)session.getAttribute("USER_SESSION")).getUserid());
		int rows = userService.changeUserInfo(user);
		JSONObject json = new JSONObject();
		if(rows>0)
			json.put("status","succeed");
		else
			json.put("status", "failed");
		return json;
	}
	/*
	 * 上传或修改用户头像
	 */
	@RequestMapping("/uploadUsercover.action")
	@ResponseBody
	public JSONObject uploadUsercover(@RequestParam MultipartFile uploadfile,HttpServletRequest request) {
		String fileName = uploadfile.getOriginalFilename();
		System.out.println(fileName);
		String dirPath = request.getServletContext().getRealPath("/upload/usercover");
		System.out.println(dirPath);
		File file = new File(dirPath);
		if(!file.exists())
			file.mkdirs();
		String newFileName = UUID.randomUUID()+"_"+fileName;
		try {
			uploadfile.transferTo(new File(dirPath+newFileName));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		json.put("usercover", dirPath+newFileName);
		return json;
		
	}
	/*
	 * 修改用户密码
	 */
	@RequestMapping(value="/changePassword.action")
	@ResponseBody
	public JSONObject changePassword(String password,HttpSession session) {
		String userid = ((User)session.getAttribute("USER_SESSION")).getUserid();
		int rows = userService.changePassword(userid,password);
		JSONObject json = new JSONObject();
		if(rows>0)
			json.put("status","succeed");
		else
			json.put("status", "failed");
		return json;
	}
//	/*
//	 * 用户退出
//	 */
//	@RequestMapping("/logout.action")
//	@ResponseBody
//	public JSONObject logout(HttpSession session) {
//		//清除session
//		session.invalidate();
//		JSONObject json=new JSONObject();
//		json.put("status", "succeed");
//		return json;
//	}
	
	/*
	 * 用户退出，管理员退出
	 */
	@RequestMapping("/logout.action")
	@ResponseBody
	public JSONObject logout(HttpSession session) {
		//清除session
		session.invalidate();
		JSONObject json=new JSONObject();
		json.put("status", "succeed");
		return json;
	}
	/*
	 * 管理员获取用户列表或者搜索用户
	 */
	@RequestMapping("/getUserList.action")
	@ResponseBody
	public JSONObject getUserList(HttpSession session,User user) {
		JSONObject json=new JSONObject();
		if(((User)session.getAttribute("USER_SESSION")).getStatus().equals("admin")) {
			List<User> list = userService.getUserList(user);
			JSONArray jarray = JSONArray.parseArray(JSON.toJSONString(list));
			json.put("users", jarray);
			json.put("status", "succeed");
		}else {
			json.put("status", "failed");
			json.put("reason", "权限不够");
		}
		return json;
	}
	/*
	 * 管理员删除普通用户
	 */
	@RequestMapping("/deleteUser.action")
	@ResponseBody
	public JSONObject deleteUser(HttpSession session, String userid) {
		JSONObject json=new JSONObject();
		if(((User)session.getAttribute("USER_SESSION")).getStatus().equals("admin")) {
			int num = userService.deleteUser(userid);
			if(num>0) {
				json.put("status", "succeed");
			}else
				json.put("status", "failed");
		}else {
			json.put("status", "failed");
			json.put("reason", "权限不够");
		}
		return json;
	}
}
